(function() {
	window.imgZoom=function(selector){
		let dom = [...document.querySelectorAll(selector)].filter(i=>i.tagName==='IMG')
		if(dom.length){
			dom.forEach(i=>{
				i.onmouseenter=ZOOM.enter
			});
		}else{
			console.log('zoom 选择器没有选中')
		}
		
	}
	window.ZOOM = {
		mounted: false,//是否在body中建立放大镜组件
		zoomStep:10//每次放大的百分比
	}
	ZOOM.zoom = function(ele) {
		// 主要作用是存入数据 等待下一步操作
		if (!this.mounted) {
			this.mount()
		}
		this.img.src = ele.src
		
		ele.onmousemove=ZOOM.move
		ele.onmousewheel= ZOOM.wheel
		
		let zoomR = getComputedStyle(ele)
		this.img.dataset.eleheight = parseInt(zoomR.height)
		this.img.dataset.elewidth = parseInt(zoomR.width)

		let imgR = getComputedStyle(this.img)
		this.img.dataset.height = parseInt(imgR.height)
		this.img.dataset.width = parseInt(imgR.width)


		let zoomZ = getComputedStyle(this.Zoom)
		this.Zoom.dataset.height = parseInt(zoomZ.height) / 2
		this.Zoom.dataset.width = parseInt(zoomZ.width) / 2

	}
	ZOOM.out=function(e){
		//出门反锁  
		e.target.onmouseenter=ZOOM.enter
		e.target.onmouseout=null
		
		ZOOM.Zoom.style.display='none'
	}
	ZOOM.enter=function(e){
		//出门反锁  
		e.target.onmouseenter=null
		e.target.onmouseout=ZOOM.out
		ZOOM.zoom(e.target)
		ZOOM.Zoom.style.display='block'
		
	}
	//滚动放大
	ZOOM.wheel=function(e) {
		e.preventDefault()
			if (e.wheelDeltaY < 0) {
				console.log('变小')
				let a = (parseInt(ZOOM.img.style.height) - ZOOM.zoomStep)
				let min = (a>50?a:parseInt(ZOOM.img.style.height))
				ZOOM.img.style.height = ( min|| '100') + '%';
			} else {
				console.log('放大')
				ZOOM.img.style.height = ((parseInt(ZOOM.img.style.height) + ZOOM.zoomStep) || '100') + '%';
			}
			let imgR = getComputedStyle(ZOOM.img)
			ZOOM.img.dataset.height = parseInt(imgR.height)
			ZOOM.img.dataset.width = parseInt(imgR.width)
			ZOOM.move(e)
		}
	//移动效果
	ZOOM.move = function(e) {
		let imgdata = ZOOM.img.dataset
		ZOOM.sizeX = e.offsetX / imgdata.elewidth
		ZOOM.sizeY = e.offsetY / imgdata.eleheight


		let zoom = ZOOM.Zoom.style
		zoom.top = e.pageY + 15 + 'px'
		zoom.left = e.pageX + 15 + 'px'

		let img = ZOOM.img.style
		
		img.top = (ZOOM.Zoom.dataset.height - ZOOM.sizeY * imgdata.height) + 'px'
		img.left = (ZOOM.Zoom.dataset.width - ZOOM.sizeX * imgdata.width) + 'px'

		let imgR = getComputedStyle(ZOOM.img)
		ZOOM.img.dataset.height = parseInt(imgR.height)
		ZOOM.img.dataset.width = parseInt(imgR.width)
	}
	//初步在body建立dom结构
	ZOOM.mount = function() {
		let zoom = document.createElement('div')
		let img = document.createElement('img')
		zoom.id = 'ZOOM'
		img.id = 'ZOOM-pic'

		this.Zoom = zoom
		this.img = img
		this.mounted = true

		zoom.appendChild(img)
		document.body.appendChild(zoom)
	}

})()
